package com.issac.messagequeue.mqserver.demo;

import com.issac.messagequeue.mqserver.common.Consumer;
import com.issac.messagequeue.mqserver.common.MqException;
import com.issac.messagequeue.mqserver.coreclass.BasicProperties;
import com.issac.messagequeue.mqserver.coreclass.ExchangeType;
import com.issac.messagequeue.mqserver.mqclient.Channel;
import com.issac.messagequeue.mqserver.mqclient.Connection;
import com.issac.messagequeue.mqserver.mqclient.ConnectionFactory;

import java.io.IOException;

/**
 * 表示一个消费者
 * 通常这个类应该在一个独立的服务器中被执行
 */
public class DemoConsumer {
    public static void main(String args[]) throws IOException, InterruptedException, MqException {
        System.out.println("启动消费者！");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(9090);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 创建交换机和队列
        channel.exchangeDeclare("testDeclare", ExchangeType.DIRECT, true, false, null);
        channel.msgQueueDeclare("testMsgQueue", true, false, false, null);

        channel.basicConsume("testMsgQueue", true, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("[消费数据]开始！");
                System.out.println("consumerTag=" + consumerTag);
                System.out.println("basicProperties=" + basicProperties);
                String messageBody = new String(body, 0, body.length);
                System.out.println("messageBody=" + messageBody);
                System.out.println("[消费数据]结束！");
            }
        });

        while (true) {
            Thread.sleep(500);
        }
    }
}
